import { ADMIN_CATEGORY } from '../actionTypes';
import { message } from 'antd';
import config from '../config';
import fetch from '../utils/fetch';
import * as R from 'ramda';

export const update = (payload) => ({
  type: ADMIN_CATEGORY,
  payload,
});

/**
 * 获取所有栏目
 */
export const getCategory = () => async (dispatch, getState) => {
  const res = await fetch({
    method: 'GET',
    url: `${config.host}/api/category/all`,
  }).catch(() => {
    message.error('网络异常');
  });
  if (res.code === 200) {
    const menus = res.data;
    if (!Array.isArray(menus)) {
      return false;
    }

    // 构建父子级关系及排序
    let topMenu = menus.filter(item => !item.parent_id).sort((a, b) => (a.rank - b.rank)).map(item => {
      item.key = item.id;
      return item;
    });
    topMenu = topMenu.map(item => {
      item['subMenu'] = menus.filter(sub => sub.parent_id && +sub.parent_id === +item.id).sort((a, b) => (a.rank - b.rank)).map(item => {
        item.key = item.id;
        return item;
      });
      return item;
    });
    dispatch(update({
      list: topMenu,
    }));
  } else {
    message.error('获取栏目失败');
  }
};

/**
 * 获取热点栏目
 */
export const getHotCategory = () => async (dispatch, getState) => {
  const res = await fetch({
    method: 'GET',
    url: `${config.host}/api/category/hot`,
  }).catch(() => {
    message.error('网络异常');
  });
  if (res.code === 200) {
    dispatch(update({
      hot: res.data,
    }));
  } else {
    message.error('获取热点栏目失败');
  }
};

/**
 * 更改标题及排序
 * @param value
 * @param id
 * @param key
 */
export const changeRankName = (value, { id, parent_id }, key) => (dispatch, getState) => {
  const { list } = getState().admin.category;

  const foo = item => {
    if (parent_id) {
      const index = R.findIndex(R.propEq('id', id))(item.subMenu);
      const arr = R.adjust(item => {
        item[key] = key === 'name' ? value : +value;
        return item;
      }, index)(item.subMenu);
      item['subMenu'] = arr;
      return item;
    } else {
      item[key] = key === 'name' ? value : +value;
      return item;
    }
  };

  const index = R.findIndex(R.propEq('id', parent_id || id))(list);
  const arr = R.adjust(foo, index)(list);

  dispatch(update({
    list: arr,
  }));
};

/**
 * 删除栏目
 * @param id
 */
export const del = (id) => async () => {
  console.log(id);
  const res = await fetch({
    method: 'POST',
    url: `${config.host}/api/category/del`,
    param: {
      id,
    }
  }).catch(() => {
    message.error('网络异常');
  });
  if (res.code === 200) {
    message.success('删除成功');
    setTimeout(() => {
      location.reload();
    }, 1200);
  } else {
    message.error('删除失败');
  }
};

/**
 * 新增栏目
 */
export const addMenu = (id) => (dispatch, getState) => {
  const { list } = getState().admin.category;
  if (/\d+/img.test(id)) {
    const index = R.findIndex(R.propEq('id', id))(list);
    if (!list[index]['subMenu']) {
      list[index]['subMenu'] = [];
    }
    list[index]['subMenu'].push({
      id: ~~(Math.random() * 100 + 1000000), // 1000000~1000100之间的数，保证id唯一，删除时鉴别使用
      parent_id: id,
      name: '',
      rank: list[index]['subMenu'].length,
    });
  } else {
    list.push({
      id: ~~(Math.random() * 100 + 1000000), // 1000000~1000100之间的数，保证id唯一，删除时鉴别使用
      parent_id: null,
      name: '',
      rank: list.length,
    });
  }
  dispatch(update({
    list,
  }));
};

/**
 * 提交数据
 */
export const submit = () => async (dispatch, getState) => {
  const { list } = getState().admin.category;
  // 拍平栏目数组
  let arr = [];
  R.forEach(item => {
    arr.push(item);
    arr = arr.concat(item.subMenu || []);
  })(list);
  const finalArr = R.map(R.pick(['id', 'parent_id', 'name', 'rank']))(arr);
  const res = await fetch({
    method: 'POST',
    url: `${config.host}/api/category/edit`,
    param: {
      list: finalArr,
    }
  }).catch(() => {
    message.error('网络异常');
  });
  if (res.code === 200) {
    message.success('更新成功');
    setTimeout(() => {
      location.reload();
    }, 1200);
  } else {
    message.error('更新失败');
  }
};

export const changeHotRank = (val, { id }) => async (dispatch, getState) => {
  const { hot } = getState().admin.category;
  const index = R.findIndex(R.propEq('id', id))(hot);
  const arr = R.adjust(item => {
    item.rank = +val;
    return item;
  }, index)(hot);
  dispatch(update({ hot: arr }));
};

export const changeHotCategory = (val, { id }) => async (dispatch, getState) => {
  const { list, hot } = getState().admin.category;

  // 构建平级栏目
  let plainCategory = [];
  list.forEach(item => {
    plainCategory.push(item);
    plainCategory = plainCategory.concat(item.subMenu || []);
  });

  const obj = R.find(R.propEq('id', val))(plainCategory);
  const index = R.findIndex(R.propEq('id', id))(hot);
  const arr = R.adjust(item => {
    item.cid = obj.id;
    item.name = obj.name;
    return item;
  }, index)(hot);
  console.log(arr);
  dispatch(update({ hot: arr }));
};

/**
 * 修改热点栏目
 */
export const updateHot = () => async (dispatch, getState) => {
  const { hot } = getState().admin.category;
  const res = await fetch({
    method: 'POST',
    url: `${config.host}/api/category/hot/edit`,
    param: {
      hot: hot,
    }
  }).catch(() => {
    message.error('网络异常');
  });
  if (res.code === 200) {
    message.success('更新成功');
    setTimeout(() => {
      location.reload();
    }, 1200);
  } else {
    message.error('更新失败');
  }
};
